import dayjs from "dayjs";
import { usePublicHooks } from "../../hooks";
import type { PaginationProps } from "@pureadmin/table";
import { getTaskLogs } from "@/api/system";
import { reactive, ref, onMounted } from "vue";

import { getFilter } from "@/utils/filter";

export function useRecord(task_id: string) {
  const form = reactive({
    job_id: task_id ? task_id : ""
  });
  const curRow = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const { tagStyle } = usePublicHooks();

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "任务ID",
      prop: "job_id",
      hide: true
    },
    {
      label: "任务名字",
      prop: "job_name"
    },
    {
      label: "状态",
      cellRenderer: scope => (
        <el-tag style={tagStyle.value(scope.row.status)}>
          {scope.row.status === 1 ? "成功" : "失败"}
        </el-tag>
      ),
      minWidth: 90
    },
    {
      label: "详细信息",
      prop: "message"
    },
    {
      label: "执行时间",
      prop: "createtime",
      minWidth: 160,
      formatter: ({ createtime }) =>
        dayjs(createtime * 1000).format("YYYY-MM-DD HH:mm:ss")
    }
  ];

  function handleSizeChange(val: number) {
    pagination.pageSize = parseInt(val as any);
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    let filter = await getFilter(form);
    let ListRequest = {
      page: pagination.currentPage,
      limit: pagination.pageSize,
      filter,
      order: "DESC"
    };

    const { data } = await getTaskLogs(ListRequest);
    dataList.value = data.list;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;

    loading.value = false;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  onMounted(async () => {
    onSearch();
  });

  return {
    form,
    isShow,
    loading,
    columns,
    rowStyle,
    dataList,
    pagination,
    onSearch,
    resetForm,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
